#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <errno.h>
#include "Mp3Decoder.hpp"
#include "AudioPlayer.hpp"

static long long get_tick(void)
{
    long long rev;
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    rev = ts.tv_sec * 1000ll + ts.tv_nsec / 1000000;
    return rev;
}
int main3()
{
    long long t1 = 0;
    FRunLoop *loop = new FRunLoop();
    Mp3Decoder *decoder = new Mp3Decoder(loop, "./1.mp3");
    decoder->stateChangeCB = [](Mp3Decoder *dec) {
        Mp3Decoder::State state = dec->getState();
        printf("mp3 new state:%s\n", Mp3Decoder::stateToString(state));
        if (state >= Mp3Decoder::State::WORKING) {
            const AudioPCMInfo *pcmInfo = dec->getPCMInfo();
            printf("Pcm info ch:%d rate:%d bit:%d\n", 
                pcmInfo->channel, pcmInfo->simplerate, pcmInfo->bitrate);
        }
    };
    FTimer *timer = new FTimer(1000, 1000, [decoder](FTimer *timer, bool repeat) {
        Mp3Decoder::State state = decoder->getState();
        printf("State state:%s\n", Mp3Decoder::stateToString(state));
    });
    loop->addTimer(timer);
    {
        FTimer *timer = new FTimer(100, 10, [loop, decoder, &t1](FTimer *timer, bool repeat) {
            uint16_t pcm[4410*2*2];
            if(decoder->getState() == Mp3Decoder::State::FINISH) {
                // printf("decode used:%lld\n", get_tick() - t1);
            }
            if (decoder->getState() <= Mp3Decoder::State::LOADING) return;
            int rev = decoder->readPCM(pcm, sizeof(pcm)/2);
            if (rev == 0) {
                if(decoder->getState() == Mp3Decoder::State::FINISH) {
                    loop->interrupt();
                }
            }
            // printf("Readed pcm:%d\n", rev);
            // decoder->printCache();
        });
        loop->addTimer(timer);
    }
    {
        FTimer *timer = new FTimer(2000, [loop, &decoder](FTimer *timer, bool repeat) {
            decoder->destroy();
            decoder = nullptr;
            loop->interrupt();
        });
        loop->addTimer(timer);
    }
    decoder->start();
    t1 = get_tick();
    while (true) {
        loop->runOnce();
        if (loop->isInterrupt()) break;
    }
    if (decoder) decoder->destroy();
    delete loop;
    return 0;
}

static void sig_(int signo)
{
    exit(0);
}
int main()
{
    signal(SIGINT, sig_);
    FRunLoop *loop = new FRunLoop();
	AudioPlayer *player = new AudioPlayer(loop, "./1.mp3");
    bool started = false;

    player->stateChangeCB = [&started](AudioPlayer *player) {
        AudioPlayer::State state = player->getState();
        printf("player state chg %s\n", AudioPlayer::stateToString(state));
        if (!started) {
            player->resume();
        }
        if (state == AudioPlayer::State::IDLE) {
            player->load();
        }
    };
	player->load();
	
    while (true) {
        loop->runOnce();
        if (loop->isInterrupt()) break;
    }
    sleep(2);
	delete loop;
}

